﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodMan.Infrastructure.Entities.Entity;
using System.Threading;
using GoodMan.Tool.Framework;

namespace GoodMan.Core.NoticeManager
{
    public static class DutyNotice
    {
        /// <summary>
        /// int : dormitoryID
        /// </summary>
        private static Dictionary<int, Queue<DutyMessage>> dict;
        static DutyNotice()
        {
            dict = new Dictionary<int, Queue<DutyMessage>>();
            List<Dormitory> dormitories = new Dormitory().FindAll();
            foreach (var item in dormitories)
            {
                dict.Add(item.Id, new Queue<DutyMessage>());
            }
        }

        public static List<DutyMessage> GetMyDutyMessage(int dormitorId, string userName)
        {
            List<DutyMessage> data = new List<DutyMessage>();
            if (dict.ContainsKey(dormitorId))
            {
                try
                {
                    Monitor.Enter(dict[dormitorId]);
                    for (int i = 0, len = dict[dormitorId].Count; i < len; i++)
                    {

                        data.Add(dict[dormitorId].Dequeue());

                    }
                    Monitor.Exit(dict[dormitorId]);
                }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.Support, LogLevel.Error, e);
                    Monitor.Exit(dict[dormitorId]);
                }
            }
            return data;
        }

        /// <summary>
        /// 执行通知
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="staff">值班人员</param>
        public static void DoNotice(Order order, User staff, User customer)
        {
            if (staff != null && staff.SystemRole == Infrastructure.Entities.Enum.UserRole.Staff)
            {
                OnlineState state = OnlineManager.GetOnlineState(staff.UserName);
                if (state == OnlineState.在线)
                {
                    Queue<DutyMessage> queue = dict[order.DormitoryID];
                    if (queue != null)
                    {
                        try
                        {
                            queue.Enqueue(new DutyMessage()
                            {
                                CreateDate = DateTime.Now,
                                Message = String.Format("用户{0}(电话：{1})购买了{2}，联系信息：{3}，需支付{4}，请尽快安排送货",
                                customer.RealName,String.IsNullOrEmpty(customer.Phone)?"":customer.Phone, 
                                order.ProductDescript, order.AssemblingInfo, order.TotalPrice),
                                OrderId = order.Id
                            });
                        }
                        catch (Exception e)
                        {
                            LogHelper.Write(CommonLogger.Support, LogLevel.Error, e);
                        }
                    }
                }
                else
                {
                    SendShortMessage(order, staff,customer);
                }
            }
        }

        private static void SendShortMessage(Order order, User staff,User customer)
        {
            try
            {
                var lik = new GoodMan.Core.ShortMessage.WebServiceSoapClient("WebServiceSoap");
                string username = "SDK-GHD-010-00170";
                string pwd = HashAlgorithm.Encrypt("SDK-GHD-010-00170" + "591783", EncryptMode.md5).ToUpper();
                string message = string.Format("用户{0}(电话：{1})\"购买了{2}，请尽快登陆管理后台查看并及时安排配送。【校生活外卖】",
                    new User().Find(order.UserName).RealName, customer.Phone, order.ProductDescript);
                string code = lik.mt(username, pwd, staff.Phone, message, "", "", "");
                LogHelper.Write(CommonLogger.Support, LogLevel.Info, message);
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Error, e);
            }
        }

        public static string GetShortMessageRemain()
        {
            var lik = new GoodMan.Core.ShortMessage.WebServiceSoapClient("WebServiceSoap");
            string username = "SDK-GHD-010-00170";
            string pwd = HashAlgorithm.Encrypt("SDK-GHD-010-00170" + "591783", EncryptMode.md5).ToUpper();
            return lik.balance(username, pwd);
        }
    }

    public class DutyMessage
    {
        public DateTime CreateDate { get; set; }
        /// <summary>
        /// 通知内容:
        /// xxxxx购买了xxxxx，需支付xxxx，请尽快安排送货
        /// xxxxx购买了快餐xxx，商家为：xxxx，待支付金额为：xxx
        /// </summary>
        public string Message { get; set; }
        public int OrderId { get; set; }
    }
}
